define([ 'backbone',
         'components/pop/base',
         'text!components/pop/templates/qrcode.html',
         'core/utils' ],
function( Backbone, Base, template, utils ) {

    return Base.extend({
        template: _.template(template),
        className: function() {
            return this.options.className;
        },
        events: {
            'click .js-btn-cancel': 'hide',
            'click .js-btn-confirm': 'triggerCallback',
            'keypress .js-txt': 'enterSave'
        },
        initialize: function(options) {
            Base.prototype.initialize.call(this, options);
            this.data = options.data;
        },
        render: function() {
            var that = this;
            var data = {};
            _.extend(data, {
                placeholder: '二维码名称'
            }, this.data);
            that.$el.html(that.template(data));
            that.el.className = that.options.className;

            that.txt = that.$el.find('.js-txt');
            return that;
        },
        positioning: function() {
            var that = this;

            that.$el.show().position({
                of: that.target,
                my: 'center top',
                at: 'center bottom',
                collision: 'none'
            });

            that.txt.focus();
        },
        setData: function(data) {
            this.data = _.extend(this.data, data);
            this.render();
        },
        reset: function(obj) {
            var callback = obj.callback,
                target = obj.target,
                trigger = obj.trigger,
                data = obj.data,
                className = obj.className;

            this.options.className = className;
            this.setCallback(callback);
            this.setTarget(target);
            this.setTrigger(trigger);
            this.setData(data);
            this.positioning();
            this.show();
        },
        enterSave: function(event) {
            if (event.which === utils.keyCode.ENTER) {
                this.triggerCallback();
                return false;
            }
        },
        triggerCallback: function() {
            var that = this;

            // @TODO 改造成 new Keyword model 出来去处理数据校验等操作
            var _name = that.txt.val();

            if (utils.isEmpty(_name)) {
                that.txt.focus();
                return false;
            };

            that.setData({
                name: _name
            });
            that.callback.call(that, that.data);
            that.hide();
        }
    });
});
